/*
 * @Author: anxia.ack anchenkai@come-future.com
 * @Date: 2025-04-14 17:02:02
 * @LastEditors: anxia.ack anchenkai@come-future.com
 * @LastEditTime: 2025-04-14 18:24:29
 * @FilePath: /free-learning/src/store/modules/upload-message.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import moment from "moment";
import { v4 as uuidv4 } from "uuid";
export interface UploadMessage {
  id: string;
  title: string;
  content: string;
  status: "success" | "error" | "uploading";
  isRead: boolean;
  createdAt: string;
}
export const useUploadMessageStore = defineStore("uploadMessage", () => {
  const uploadMessage = ref<UploadMessage[]>(
    JSON.parse(localStorage.getItem("uploadMessage") || "[]")
  );

  function addUploadMessage(title: string, content: string): UploadMessage {
    const message: UploadMessage = {
      id: uuidv4(),
      title,
      content,
      isRead: false,
      status: "uploading",
      createdAt: moment().format("YYYY-MM-DD HH:mm:ss"),
    };
    uploadMessage.value.push(message);
    localStorage.setItem("uploadMessage", JSON.stringify(uploadMessage.value));
    return message;
  }
  function readUploadMessage(id: string) {
    uploadMessage.value = uploadMessage.value.map((item) => {
      if (item.id === id) {
        item.isRead = true;
      }
      return item;
    });
    localStorage.setItem("uploadMessage", JSON.stringify(uploadMessage.value));
  }
  function clearUploadMessage() {
    uploadMessage.value = [];
    localStorage.setItem("uploadMessage", JSON.stringify(uploadMessage.value));
  }
  function updateUploadMessage(id: string, title: string, content: string) {
    uploadMessage.value = uploadMessage.value.map((item) => {
      if (item.id === id) {
        item.title = title;
        item.content = content;
        item.isRead = false;
      }
      return item;
    });
    localStorage.setItem("uploadMessage", JSON.stringify(uploadMessage.value));
  }
  function delUploadMessage(id: string) {
    uploadMessage.value = uploadMessage.value.filter((item) => item.id !== id);
    localStorage.setItem("uploadMessage", JSON.stringify(uploadMessage.value));
  }

  function uploadSuccess(id: string) {
    uploadMessage.value = uploadMessage.value.map((item) => {
      if (item.id === id) {
        item.status = "success";
      }
      return item;
    });
    localStorage.setItem("uploadMessage", JSON.stringify(uploadMessage.value));
  }
  function uploadError(id: string) {
    uploadMessage.value = uploadMessage.value.map((item) => {
      if (item.id === id) {
        item.status = "error";
      }
      return item;
    });
  }
  return {
    uploadMessage,
    addUploadMessage,
    readUploadMessage,
    delUploadMessage,
    clearUploadMessage,
    uploadSuccess,
    uploadError,
    updateUploadMessage,
  };
});
